#!/bin/bash

# Author:   Andrey Dibrov (andry at inbox dot ru)

# Bash entry point script.
#
# Script can find a version of a bash shell executable and call the interpreter
# from the "/usr/local/bin" directory if it exists, otherwise would call from
# the "/bin" directory bypassing any user mount point redirection that may
# exist on the way (useful in cygwin/msys/mingw contexts).
#

# Script both for execution and inclusion.
[[ -n "$BASH" ]] || return 0 || exit 0 # exit to avoid continue if the return can not be called

if [[ -z "$SOURCE_TACKLELIB_BASH_TACKLELIB_SH" || SOURCE_TACKLELIB_BASH_TACKLELIB_SH -eq 0 ]]; then
  # builtin search
  for BASH_SOURCE_DIR in "/usr/local/bin" "/usr/bin" "/bin"; do
    [[ -f "$BASH_SOURCE_DIR/bash_tacklelib" ]] && {
      source "$BASH_SOURCE_DIR/bash_tacklelib" || exit $?
      break
    }
  done
fi

if [[ -z "$BASH_LINENO" || BASH_LINENO[0] -eq 0 ]]; then
  # Script was not included, then execute it.

  if [[ -z "$BASH_ENTRY_FILE" || ! -f "$BASH_ENTRY_FILE" ]]; then
    tkl_bash_entry "/usr/local/bin/bash"
  fi

  if [[ -z "$BASH_ENTRY_FILE" || ! -f "$BASH_ENTRY_FILE" ]]; then
    tkl_bash_entry "/bin/bash"
  fi

  if [[ -n "$BASH_ENTRY_FILE" ]]; then
    # do cache path to shell to avoid redundant execution in a child shells
    "$BASH_ENTRY_FILE" "$@"
  else
    /bin/bash "$@"
  fi

  # always exit with current exit code
  tkl_exit
fi
